Ext.onReady(function(){
	Ext.QuickTips.init();
	/*
	var radioGroup = {
		xtype: 'fieldset',
        title: '请选择一个您喜欢的图标',
        // in this section we use the form layout that will aggregate all of the fields
        // into a single table, rather than one table per field.
        layout: 'form',
		collapsible: true,
		border : true,
        items: [{
        	 xtype: 'radiogroup',
        	 columns: 6,
             items: [
                 {boxLabel: ' ',name: 'rb-auto', boxLabelCls: "Accept",inputValue: 1},
                 {boxLabel: 'Item 2', name: 'rb-auto', inputValue: 2, checked: true},
                 {boxLabel: 'Item 3', name: 'rb-auto', inputValue: 3},
                 {boxLabel: 'Item 4', name: 'rb-auto', inputValue: 4},
                 {boxLabel: 'Item 5', name: 'rb-auto', inputValue: 5},
                 {boxLabel: 'Item 6', name: 'rb-auto', inputValue: 6},
                 {boxLabel: 'Item 7', name: 'rb-auto', inputValue: 7},
                 {boxLabel: 'Item 8', name: 'rb-auto', inputValue: 8},
                 {boxLabel: 'Item 9', name: 'rb-auto', inputValue: 9},
                 {boxLabel: 'Item 10', name: 'rb-auto', inputValue: 10},
                 {boxLabel: 'Item 11', name: 'rb-auto2', inputValue: 3},
                 {boxLabel: 'Item 12', name: 'rb-auto2', inputValue: 4},
                 {boxLabel: 'Item 13', name: 'rb-auto2', inputValue: 5},
                 {boxLabel: 'Item 14', name: 'rb-auto2', inputValue: 6},
                 {boxLabel: 'Item 15', name: 'rb-auto2', inputValue: 7},
                 {boxLabel: 'Item 16', name: 'rb-auto2', inputValue: 8},
                 {boxLabel: 'Item 17', name: 'rb-auto2', inputValue: 9},
                 {boxLabel: 'Item 18', name: 'rb-auto2', inputValue: 10}
             ]
        }]
	};
	
	var iconForm =Ext.create('Ext.form.Panel', {
		border : false,
		width: 700,
		items:[radioGroup]
	});
	
	var iconWin = Ext.create('Ext.window.Window',{
		layout:'fit',
		width: 750,
		height:350,
		closeAction:'hide',
		modal: true,
		plain: true,
		title: "编辑用户",
		iconCls: "Vcardedit",
		items: [iconForm]
	});*/
	
	// 定义右键菜单
	var contextMenu = Ext.create("Ext.menu.Menu",{
		width: 100,
	    plain: true,
	    floating: true,  // usually you want this set to True (default)
	    renderTo: Ext.getBody(),  // usually rendered by it's containing component
		items : [{
			id:'parternNode',
			text : '添加根节点',
			iconCls:'Arrowup',
			hidden:true,
			handler : function(){
				contentPanel.form.reset();
				Ext.MessageBox.prompt("请输入新的根节点名称","",
				function(e,text){
					if(e=="ok"){
//					  var leaf = tree.getSelectionModel().getLastSelected().raw.leaf;
					  var menuFatherId = tree.getSelectionModel().getLastSelected().raw.fatherId;
					  var menuId = tree.getSelectionModel().getLastSelected().raw.menu_id;
					  Ext.Ajax.request({
						  url: '/menu/saveMenu?menuFatherId='+menuFatherId+"&text="+text+"&menuId="+menuId+"&nodeType=father",
						  success:function(request){
							  var respText = Ext.decode(request.responseText);
							  if(respText.code != 'OK') {
								  Ext.Msg.alert('添加子节点失败', respText.message+"("+respText.code+")");
							  }else{
								  Ext.Msg.alert('添加节点成功', '添加节点成功，请点击树形菜单节点修改详细信息。');
								  store.reload();
							  }
						  },
						  failure:function(res){
							  var respText = Ext.decode(res.responseText);
							  Ext.Msg.alert('添加子节点失败', respText.message+"("+respText.code+")");
						  }
					  });
					}else{
						  //alert("取消了");
					}
				});
			}
		},{
			id:'childNode',
			text : '添加子节点',
			hidden:true,
			iconCls:'Arrowdown',
			handler : function(){
				contentPanel.form.reset();
				Ext.MessageBox.prompt("请输入新的子节点名称","",
				function(e,text){
					if(e=="ok"){
//					  var leaf = tree.getSelectionModel().getLastSelected().raw.leaf;
					  var menuFatherId = tree.getSelectionModel().getLastSelected().raw.fatherId;
					  var menuId = tree.getSelectionModel().getLastSelected().raw.menu_id;
					  Ext.Ajax.request({
						  url: '/menu/saveMenu?menuFatherId='+menuFatherId+"&text="+text+"&menuId="+menuId+"&nodeType=node",
						  success:function(request){
							  var respText = Ext.decode(request.responseText);
							  if(respText.code != 'OK') {
								  Ext.Msg.alert('添加子节点失败', respText.message+"("+respText.code+")");
							  }else{
								  Ext.Msg.alert('添加节点成功', '添加节点成功，请点击树形菜单节点修改详细信息。');
								  store.reload();
							  }
						  },
						  failure:function(){
							  var respText = Ext.decode(res.responseText);
							  Ext.Msg.alert('添加子节点失败', respText.message+"("+respText.code+")");
						  }
					  });
					}
					else{
						  //alert("取消了");
					}
				});
			}
		},{
			id:'delNode',
			text : '删除当前节点',
			hidden:true,
			iconCls:'Bugdelete',
			handler : function(){
				Ext.MessageBox.confirm("删除提示", "确定要删除当前节点吗？",function(btn){
					if(btn=='yes'){
						contentPanel.form.reset();
						var menu_id = tree.getSelectionModel().getLastSelected().raw.menu_id;
						Ext.Ajax.request({
							  url: '/menu/deleteMenu?menu_id='+menu_id,
							  success:function(response,request){
								  var respText = Ext.JSON.decode(response.responseText);
									if(respText.code != 'OK') {
										Ext.Msg.alert('删除节点失败', respText.message + "（" + respText.code + "）");
									} else {
										Ext.Msg.alert('删除节点成功', '删除节点成功');
										store.reload();
									}
							  },
							  failure:function(res){
								  var respText = Ext.decode(res.responseText);
								  Ext.Msg.alert('删除节点失败', respText.message+"("+respText.code+")");
							  }
						  });
					}    
				}); 
			}  
		},{
			id:'refresh',
			text : '刷新',
			hidden:true,
			iconCls: "Arrowrefreshsmall",
			handler : function(){
				store.reload();
			}  
		}] 
	});
	
	// 绑定节点右键菜单功能
	function treeContextHandler(view, record, item, index, event, options) {
		event.preventDefault();//一说是组织浏览器的默认右键事件，二说是防止两次出现右键画面（怎么可能出现两次）
		contextMenu.showAt(event.getXY());//显示右键菜单
	}
	
	var contentPanel = Ext.create('Ext.form.Panel', {
		 region : 'center',
		 title	: '菜单详细内容',
		 id : 'menuForm',  
		 border : true,
		 defaults:{  
	         margin:'10 0 0 20'  
	     }, 
	     fieldDefaults: {
	            labelAlign: 'left',
	            labelWidth: 90,
	            anchor: '95%'
	     },
		 defaultType: 'textfield',
		 items: [
		    {
		    	name:'menu_id',
		    	hidden:true
		    },
		    {
				fieldLabel: '菜单名称',
				name: 'text',
				maxLengthText :'菜单名称长度不能超过20',  
				blankText:"菜单名称不能为空，请填写！",
	            maxLength : 20,
				allowBlank:false,
				inputType: 'menuName'
			},{
				fieldLabel: 'URL',
				name: 'url'
			},{
				fieldLabel: '图标',
				//id:'memo',
				//xtype:'triggerfield',
				//triggerCls: "ux-form-search-trigger",
				//hideTrigger : false,//不隐藏触发按钮
				//emptyText: '不填写图标，会有默认图标……',
				name: 'iconCls',
				maxLengthText :'图标名称长度不能超过20',  
				/*onTriggerClick : function(){
					iconWin.show();
					var memo = testForm.getForm().findField('memo');//取得输入控件
					alert(memo.getValue());//取得控件值
					Ext.getCmp('memo').setValue('test');
				}*/
			},{
				fieldLabel: '描述',
				xtype: 'textareafield',
				name: 'description'
			},{
				fieldLabel: '操作指南',
				xtype: 'textareafield',
				disabled:true,
				name: 'beizhu',
				value:'请点击左边菜单树节点后再编辑详细信息，添加节点不支持3级及以上更高的节点'
			}
			],
			buttons: [{
				id:'saveMenu',
				text: '保&nbsp;存',
				hidden: true,
				handler: function() {
					var menuForm = Ext.getCmp('menuForm');
					if(menuForm.form.isValid()) {
//						var values = menuForm.getForm().getValues();
//						var menuUrl = menuForm.getForm().getValues().url;
//						var menuIconCls = menuForm.getForm().getValues().iconCls;
//						var menuDescription = menuForm.getForm().getValues().description;
//						alert("menuName:"+menuName+",menuUrl:"+menuUrl+",menuIconCls:"+menuIconCls+",menuDescription:"+menuDescription);
						menuForm.form.submit({
							url: '/menu/updateMenu',
							method: 'POST',
							success: function(response, action) {
								Ext.Msg.alert('修改菜单信息成功', '菜单信息修改成功，请刷新页面或者重新登录后观察效果');
								store.reload();
								//tree.expandAll();//展开所有节点
							},
							failure: function(form, action) {
								switch (action.failureType) {
									case Ext.form.Action.CLIENT_INVALID:
										Ext.Msg.alert('修改失败', '数据字段格式错误！');
										break;
									case Ext.form.Action.CONNECT_FAILURE:
										Ext.Msg.alert('修改失败', '连接异常！');
										break;
									case Ext.form.Action.SERVER_INVALID:
									   Ext.Msg.alert('修改失败', action.result.message);
							   }
							},
							waitMsg: '数据保存中，请稍候...'
						});
					} else {
						Ext.Msg.alert('系统提示', '请填写完整再提交！');
					}
				}
			},{
				text: '刷&nbsp;新',
				handler: function() {
					win.hide();
				}
			}]
	});
	
	var store = Ext.create('Ext.data.TreeStore', { 
		autoLoad : true,
		proxy : {
             type : 'ajax',
             url : '/menu/showMenuByConf',
             reader : {
                 type : 'json',
                 root : 'children'//数据  
             }, 
             //传参  
             extraParams : {  
                 id : 'null'  
             }
         },
	     root : {
	         text : '管理菜单',
	         expanded : true 
	     },
	     listeners : {
	         'beforeexpand' : function(node,eOpts){  
	        	 //点击父亲节点的菜单会将节点的id通过ajax请求，将到后台  
	             this.proxy.extraParams.id = node.raw.id;
	         }  
	     }  
	});
	
	var tree = Ext.create("Ext.tree.Panel", {
		region		: 'west',
		title		: '菜单',
		width		: 300,
		store		: store,
		lines		: false,
		useArrows	: true,
		rootVisible	: false,
		collapsible : true, // 是否折叠
		split 		: true,
        tbar: [{
            text: '刷新',
            iconCls: "Arrowrefreshsmall",
            scope: this,
            handler: function(){
            	store.reload();
            }
        }, '-', {
            text: '帮助',
            iconCls: "Help",
            scope: this,
            listeners: {
	    		   click:function(){
	    			   Ext.Msg.alert('帮助指引', '试试在菜单树上右键操作吧！（注：不支持3级及以上更高的节点）');
	    		   }
	    	}
        }]
	});
	
	tree.expandAll();//展开所有节点
    //tree.collapseAll(); //关闭所有节点
	tree.on('itemcontextmenu', treeContextHandler); 
	tree.on('itemclick', function(view,record){
		var menuId = record.raw.menu_id;
		contentPanel.form.reset();
		contentPanel.form.load({
			url: '/menu/loadMenu?menuId=' + menuId,
			method:'POST',
			waitMsg : '正在载入数据...',
			reader: Ext.create('Ext.data.JsonReader', {
				 type  : 'json',
				 root  : 'data'
			 }),
			success : function(form,action) {
				
			},
			failure : function(form,action) {
				Ext.Msg.alert('编辑菜单', '数据读取失败');
			}
		});
	});
	
	tree.getView().on('render', function(view) {
        view.tip = Ext.create('Ext.tip.ToolTip', {
            // 所有的目标元素
            target: view.el,
            // 每个网格行导致其自己单独的显示和隐藏。
            delegate: view.itemSelector,
            // 在行上移动不能隐藏提示框
            trackMouse: true,
            // 立即呈现，tip.body可参照首秀前。
            renderTo: Ext.getBody(),
            //自定义的样式
            //baseCls:"tip-body",
            height:30,
            listeners: {
                // 当元素被显示时动态改变内容.
                beforeshow: function updateTipBody(tip) {
                    tip.update('点右键试试？');
                }
            }
        });
    });
	Ext.Ajax.request({
        url: '/menuPer/getMenuPer',
        timeout: 30000,
      	success: function(response,options) {
      		var respText = Ext.JSON.decode(response.responseText);
      		if(respText.code == 'OK') {
      			var rec = respText.data;
      			for(var i=0; i<rec.length; i++){
      				if(rec[i].kind=='parternNode'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('parternNode').hide();
      					}else{
      						Ext.getCmp('parternNode').show();
      					}
      				}
      				if(rec[i].kind=='childNode'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('childNode').hide();
      					}else{
      						Ext.getCmp('childNode').show();
      					}
      				}
      				if(rec[i].kind=='delNode'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('delNode').hide();
      					}else{
      						Ext.getCmp('delNode').show();
      					}
      				}
      				if(rec[i].kind=='refresh'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('refresh').hide();
      					}else{
      						Ext.getCmp('refresh').show();
      					}
      				}
      				if(rec[i].kind=='saveMenu'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('saveMenu').hide();
      					}else{
      						Ext.getCmp('saveMenu').show();
      					}
      				}
      			}
      		}
      	},
      	failure: function(response,options) {}
      });

	
	// 整体架构容器
	Ext.create("Ext.container.Viewport", {
		layout : 'border',
		id     : 'winView',
		border: false,
		items : [tree,contentPanel]
	});
});